use reqwest::{Client, ClientBuilder};
use std::time::Duration;

/// Create a configured HTTP client with timeout and user-agent
pub fn build_client() -> anyhow::Result<Client> {
    use reqwest::header::{HeaderMap, HeaderValue, REFERER, ACCEPT, ACCEPT_LANGUAGE};
    
    // 添加默认请求头，模拟浏览器行为
    let mut headers = HeaderMap::new();
    headers.insert(REFERER, HeaderValue::from_static("https://stock.finance.sina.com.cn/"));
    headers.insert(ACCEPT, HeaderValue::from_static("*/*"));
    headers.insert(ACCEPT_LANGUAGE, HeaderValue::from_static("zh-CN,zh;q=0.9,en;q=0.8"));
    
    let client = ClientBuilder::new()
        .timeout(Duration::from_secs(30))
        .connect_timeout(Duration::from_secs(10))
        .pool_idle_timeout(Duration::from_secs(90))
        .pool_max_idle_per_host(10)
        .default_headers(headers)  // 添加默认请求头
        .user_agent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36")
        .gzip(true)
        .brotli(true)
        .tcp_keepalive(Duration::from_secs(60))
        .build()?;
    Ok(client)
}

/// Build client with custom headers
pub fn build_client_with_headers(headers: Vec<(&str, &str)>) -> anyhow::Result<Client> {
    let mut builder = ClientBuilder::new()
        .timeout(Duration::from_secs(30))
        .gzip(true)
        .brotli(true);
    
    let mut header_map = reqwest::header::HeaderMap::new();
    for (key, value) in headers {
        header_map.insert(
            reqwest::header::HeaderName::from_bytes(key.as_bytes())?,
            reqwest::header::HeaderValue::from_str(value)?,
        );
    }
    builder = builder.default_headers(header_map);
    Ok(builder.build()?)
}
